<template>
  <div class="the-page">
    <el-form ref="formRef" :rules="formRules" :model="upload.post" class="demo-form-inline" label-width="100px">

      <el-form-item label="用户" prop="customerId">
        <el-select v-model="upload.post.customerId" placeholder="请选择用户" style="width: 360px" filterable>
          <el-option v-for="item in props.customerList" :key="item.id" :label="`${item.id}-${item.name} (${item.phone})`" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input v-model="upload.post.title" show-word-limit maxlength="30" placeholder="输入标题"></el-input>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="upload.post.description" show-word-limit type="textarea" maxlength="1000" :rows="6" placeholder="输入内容描述"></el-input>
      </el-form-item>

      <el-form-item label="视频">
        <upload-aliyun-auth v-model:uploadStatus="upload.status" type="video" @video:info="uploadFn.infoBack" @image:info="uploadFn.coverBack" @video:success="uploadFn.successBack" @video:ready="uploadFn.readyBack" @clear="uploadFn.readyBack(0)" @video:progress="uploadFn.progressBack($event,'video')" @image:progress="uploadFn.progressBack($event,'image')"></upload-aliyun-auth>
      </el-form-item>

      <el-form-item label="位置" prop="location">
        <span>请输入经度：</span>
        <el-input-number style="width:240px;margin: 0 8px 8px 0;" v-model="upload.post.longitude" placeholder="请输入经度" controls-position="right"></el-input-number>
        <span>请输入纬度：</span>
        <el-input-number style="width:240px;margin: 0 8px 8px 0;" v-model="upload.post.latitude" placeholder="请输入纬度" controls-position="right"></el-input-number>
        <el-input v-model="upload.post.location" placeholder="请输入位置地名"></el-input>
      </el-form-item>

      <el-form-item label="标签">
        <el-select v-model="upload.post.relatedTopic" multiple placeholder="请选择话题标签" style="width: 360px" filterable>
          <el-option v-for="item in props.tagsList" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>

      <el-form-item style="text-align:center">
        <el-button type="primary" plain @click="uploadFn.submitPre(formRef)">提交</el-button>
      </el-form-item>

    </el-form>

    <el-dialog v-model="upload.isLoading" :close-on-click-modal="false" :show-close="false">
      <div>
        <span>视频上传进度：</span>
        <el-progress :percentage="upload.videoProgress" :color="[{ color: '#1989fa', percentage: 99 },{ color: '#67c23a', percentage: 100 }]" />
      </div>
      <div style="margin-top:24px;">
        <span>封面上传进度：</span>
        <el-progress :percentage="upload.imageProgress" :color="[{ color: '#1989fa', percentage: 99 },{ color: '#67c23a', percentage: 100 }]" />
      </div>
 
    </el-dialog>
  </div>
</template>
<script setup>
import uploadAliyunAuth from "@/components/Upload/aliyunAuth";
import { ref, reactive, onMounted } from "vue";
import { uploadImageOrVideo } from "@/api/operation";
import { ElMessage } from 'element-plus';
const props = defineProps({
  customerList: {
    default: ()=>[],
    type: Object,
  },
  tagsList: {
    default: ()=>[],
    type: Object,
  },
})
const formRef = ref();
const formRules = reactive({
  customerId: [{ required: true, message: "请输入用户id", trigger: "blur" ,validator:(rule, value, callback) => {
    if (!value) {
      callback(new Error('请填写用户id！'))
    } else if (!/^\d+/.test(value)) {
      callback(new Error("请检查用户id格式！"))
    } else {
      callback()
    }
  }}],
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
});

const { $data: upload, $fn: uploadFn } = (() => {
  const backup = {
    post:{
      type: "video",
      customerId: null,
      longitude: undefined,
      latitude: undefined,
      location: "",
      // musicId: "",
      // musicName: "",
      title: "",//标题
      description: "",//描述
      coverImageId: "",//封面图id
      relatedTopic: "",
      video: {
        videoId: "",
        format: "mp4",
        duration: 0,
        size: 0,
      },
    }
  }
  const $data = reactive({
    isLoading: false,
    fileIsReady: false,
    post:{...backup.post},
    coverReady: false,
    status:"",

    videoProgress: 0,
    imageProgress: 0,
  });
  const $fn = {
    successBack(infos){
      console.log("successBack",infos)
      for(let info of infos){
        if(info.isImage){
          $data.post.coverImageId = info.videoId;
        }else{
          $data.post.video.videoId=info.videoId;
        }
      }
      $fn.submitData();
    },
    readyBack(num){
      $data.fileIsReady = !!num;
    },
    infoBack(info){
      console.log("infoBack",info)
      $data.post.video.duration = info.duration||0;
      $data.post.video.size = info.size||0;
    },
    coverBack(value){
      $data.coverReady = value;
    },
    progressBack(value,type){
      console.log("progressBack",type,value)
      $data[type+"Progress"] = parseInt(value*100);
    },
    submitPre(formRef) {
      if (!formRef) return;
      formRef.validate((valid) => {
        if (valid) {
          if(!$data.fileIsReady){
            ElMessage.error("请选择文件！");
            return;
          }
          if(!$data.coverReady){
            ElMessage.warning("视频或封面图错误，请处理后再提交！");
            return;
          }
          $data.isLoading = true;
          $data.status = "upload";
        }
      });
    },
    submitData() {
      // 数据验证
      let req = {
        ...$data.post,
        relatedTopic: (()=>{
          if(!$data.post.relatedTopic?.length){
            return "";
          }else{
            return $data.post.relatedTopic.join(",")
          }
        })(),
      };
      console.log("upload req:",req);
      uploadImageOrVideo(req).then((res) => {
        if (res.code === 0) {
          console.log("upload res:",res);
          ElMessage.success("上传成功！");
          $data.status = "clear";
          $fn.resetPost();
        }
        $data.isLoading = false;
      });
    },
    resetPost(){
      $data.post = {...backup.post};
    }
  }
  return {
    $data,
    $fn,
  }
})();
</script>
<script>
export default {
  name: "uploadContent",
};
</script>

<style scoped lang="scss">
.the-page{
  background-color: #ffffff;
  padding: 12px;
}
</style>